package com.zr.task.activity;


import android.app.Dialog;
import android.text.Editable;
import android.text.InputType;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.zh.baselibrary.base.BasePresenter;
import com.zh.baselibrary.base.BaseRecyclerAdapter;
import com.zh.baselibrary.base.CountTimeBaseActivity;
import com.zh.baselibrary.constant.ExtraName;
import com.zh.baselibrary.utils.ListUtils;
import com.zh.baselibrary.utils.LogUtils;
import com.zh.baselibrary.utils.TTSUtils;
import com.zh.baselibrary.views.ToastView;
import com.zh.model.task.home.SwipingCardResBean;
import com.zh.model.task.home.ValidateBean;
import com.zh.model.task.home.ValidateResBean;
import com.zh.model.task.relation.AssociateTag;
import com.zr.task.R;
import com.zr.task.adapter.RelationHomeworkAdapter;
import com.zr.task.dialog.ChooseDialog;
import com.zr.task.dialog.ChooseSubjectDialog;
import com.zr.task.presenter.RelationPresenter;
import com.zr.task.presenter.view.RelationView;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;
import butterknife.OnTextChanged;

public class RelationHomeworkActivity extends CountTimeBaseActivity<RelationPresenter> implements RelationView, BaseRecyclerAdapter.OnItemViewClickListener, ChooseSubjectDialog.OnClickListener {

    @BindView(R.id.et_radio)
    EditText mEtRadio;
    @BindView(R.id.tv_success)
    TextView mTvSuccess;
    @BindView(R.id.tv_name)
    TextView mTvName;
    @BindView(R.id.rl_notice)
    RelativeLayout mRlNotice;
    @BindView(R.id.ll_count_time)
    LinearLayout mLlCountTime;
    @BindView(R.id.rl_error)
    RelativeLayout mRlError;
    @BindView(R.id.tv_notice_content)
    TextView mTvNoticeContent;
    @BindView(R.id.tv_time)
    TextView mTvTime;
    @BindView(R.id.rv_ralation)
    RecyclerView mRvRalation;
    @BindView(R.id.rl_title)
    RelativeLayout titleRelative;
    RelationHomeworkAdapter mAdapter;
    SwipingCardResBean mBean;
    List<ValidateBean> adapterList = new ArrayList<>();
    List<String> codeList = new ArrayList<>();
    List<AssociateTag> associateTagList = new ArrayList<>();
    ChooseSubjectDialog chooseSubjectDialog;
    private boolean isShow = false;
    List<String> subjectList = Arrays.asList("语文", "数学", "英语", "物理", "化学", "生物", "政治", "历史", "地理");

    @Override
    protected int getLayoutId() {
        return R.layout.activity_relation_homework;
    }

    @Override
    protected void init() {
        mBean = (SwipingCardResBean) getIntent().getSerializableExtra(ExtraName.KEY_DATA);
        int color = getIntent().getIntExtra(ExtraName.KEY_COLOR,0);
        if(color!=0)
            titleRelative.setBackgroundColor(color);
        mTvName.setText(mBean == null ? null : "您好，" + mBean.getName());
        mAdapter = new RelationHomeworkAdapter(adapterList);
        mAdapter.setOnItemViewClickListener(this);
        mRvRalation.setLayoutManager(new LinearLayoutManager(this));
        mRvRalation.setAdapter(mAdapter);

        mEtRadio.setFocusable(true);
        int inType = mEtRadio.getInputType();
        mEtRadio.setInputType(InputType.TYPE_NULL);
        mEtRadio.setInputType(inType);
        mEtRadio.requestFocus();
        TTSUtils.getInstance().speak(getString(R.string.to_relate));
    }

    @OnTextChanged(R.id.et_radio)
    public void onTextChanged(CharSequence text, int start, int before, int count) {
        String str = mEtRadio.getText().toString();
        LogUtils.e("str:" + str+"count:"+count+"start:"+start+"before:"+before);
        if (str.contains("\n")) {
            if (mRlNotice.getVisibility() == View.VISIBLE) {
                mRlNotice.setVisibility(View.GONE);
                mLlCountTime.setVisibility(View.GONE);
            }

            String content = str.split("\n")[0];
            LogUtils.e("content:" + content);
            LogUtils.e("size:" + content.length());
            if (codeList.contains(content)) {
                ToastView.showShort("该标签已添加");
            } else {
                if (content.length() == 12) {
                    mPresenter.identifyCode(new ValidateResBean(content, mBean.getId(), 0));
                    countTimeReset();
                } else {
                    if (chooseSubjectDialog != null && isShow) {
                        chooseSubjectDialog.cancel();
                    }
                    if (chooseSubjectDialog == null)
                        chooseSubjectDialog = new ChooseSubjectDialog(RelationHomeworkActivity.this, R.style.DialogTheme, content, this);
                    else
                        chooseSubjectDialog.setRadioCode(content);

                    chooseSubjectDialog.show();
                    isShow = true;

                }
            }
            mEtRadio.setText("");
            int inType = mEtRadio.getInputType();
            mEtRadio.setInputType(InputType.TYPE_NULL);
            mEtRadio.setInputType(inType);
        }
    }

    @OnClick({R.id.iv_back, R.id.tv_submit, R.id.tv_sure})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.iv_back:
                new ChooseDialog(this, R.style.DialogTheme, "返回后不保存数据，确认返回？", new ChooseDialog.OnClickListener() {
                    @Override
                    public void onClick(View view, Dialog dialog) {
                        finish();
                    }
                }).show();

                break;
            case R.id.tv_submit:
                if (adapterList.size() == 0) {
                    showErrorMsg("请先扫描作业本，进行绑定");
                    return;
                }
                mPresenter.associate(mBean.getId() + "", associateTagList);
                break;
            case R.id.tv_sure:
                mRlNotice.setVisibility(View.GONE);
                break;
        }
    }

    @Override
    protected RelationPresenter createPresenter() {
        return new RelationPresenter();
    }

    //删除
    @Override
    public void onItemViewClick(View v, int position) {
        LogUtils.e("click item");
        adapterList.remove(position);
        codeList.remove(position);
        associateTagList.remove(position);
        mAdapter.notifyDataSetChanged();
        mTvSuccess.setText(("已扫描" + mAdapter.getItemCount() + "本"));
    }

    @Override
    public void timeFinish() {
        finish();
    }

    @Override
    public void timeTick(Long millisUntilFinished) {
        mTvTime.setText(((millisUntilFinished / 1000) + "s"));
    }

    public void showErrorMsg(String msg) {
        mRlNotice.setVisibility(View.VISIBLE);
        mRlError.setVisibility(View.VISIBLE);
        mTvNoticeContent.setText(msg);

    }

    public void countTimeReset() {
        countTimer.cancel();
        timeStart();
    }

    @Override
    public void rediaCodeValidateSuccess(ValidateBean bean) {
        countTimeReset();
        codeList.add(bean.getRadioCode());
        associateTagList.add(new AssociateTag(bean.getRadioCode(), bean.getSubjectId()));
        adapterList.add(bean);
        mAdapter.notifyDataSetChanged();
        mRvRalation.smoothScrollToPosition(mAdapter.getItemCount() - 1);
        mTvSuccess.setText(("已扫描" + mAdapter.getItemCount() + "本"));
    }

    @Override
    public void onHint(String hint) {
        countTimeReset();
        showErrorMsg(hint);
        if(hint.contains("无法使用"))
            TTSUtils.getInstance().speak(getString(R.string.relate_error_more));
        else if(hint.contains("关联"))
            TTSUtils.getInstance().speak(getString(R.string.relate_error));
    }


    @Override
    public void associateSuccess() {
        finish();
    }

    @Override
    public void onClick(ValidateBean validateBean) {
            isShow = false;
            int id = subjectList.indexOf(validateBean.getSubjectName()) + 1;
            mPresenter.identifyCode(new ValidateResBean(validateBean.getRadioCode(), mBean.getId(), id) );

    }

    @Override
    public void onCancel() {
         isShow = false;
    }
}
